﻿using UnityEngine;
using System.Runtime.CompilerServices;
using Core.Extension.UIAnimation;
using Core.Mgr;
using Core.Mgrs;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

namespace Core.Base.UI
{
    /// <summary>
    /// UI面板的基类
    /// </summary>
    public class BaseUI : MonoBehaviour
    {
        private UIAttribute _uiAttribute;

        /// <summary>
        /// 当前UI在Close时是否缓存
        /// </summary>
        public bool IsCache => _uiAttribute.IsCache;

        /// <summary>
        /// 当前UI的Addressable句柄
        /// </summary>
        public AsyncOperationHandle<GameObject> aaHandle;

        private UIAnimation _uiAnimation;

        public virtual void OnInit(UIAttribute uiAttribute)
        {
            _uiAttribute = uiAttribute;
            gameObject.SetActive(false);
            _uiAnimation = GetComponent<UIAnimation>();
        }

        public virtual void OnOpen(ITuple tuple = null)
        {
            gameObject.SetActive(true);
            if (_uiAnimation != null) _uiAnimation.Show();
        }

        public virtual void OnClose()
        {
            if (_uiAnimation != null)
            {
                _uiAnimation.Hide(Hide);
            }
            else
            {
                Hide();
            }
        }

        void Hide()
        {
            if (!IsCache)
            {
                Addressables.Release(aaHandle);
                UIMgr.Ins.MemoryListRemoveItem(this);
                Destroy(gameObject);
            }
            else
                gameObject.SetActive(false);

            Util.ClearMemory();
        }
    }
}